// 引入封装的网络请求工具
import https from '../../../utils/https.js'; // 路径根据实际项目结构调整

Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectedDoor: 0,
    distance: 25,
    distancePercent: 75,
    distanceStatus: "良好",
    isOpening: false,
    openSuccess: false,
    doorList: [],          // 门列表
    communityList: [],     // 小区列表
    selectedCommunity: null,  // 当前选中的小区
    selectedCommunityIndex: 0, // 当前选中的小区索引
    residentId: null       // 住户ID
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log('手机开门页面加载完成');
    
    // 从本地存储获取登录用户的residentId
    const residentId = wx.getStorageSync('residentId');
    if (residentId) {
      this.setData({ residentId });
      this.loadUserHouses(residentId);
    } else {
      // 如果没有residentId，跳转到登录页
      wx.navigateTo({
        url: '/pages/login/login'
      });
    }
  },

  // 加载用户的房屋信息
  loadUserHouses: function(residentId) {
    // 使用https.get替换wx.request
    https.get(`opendoor/houses/${residentId}`)
      .then(res => {
        if (res.code === 200 && res.data.length > 0) {
          const houses = res.data;
          // 提取所有小区ID（去重）
          const communityIds = [...new Set(houses.map(house => house.communityId))];
          this.loadCommunities(communityIds);
        } else {
          wx.showToast({
            title: '未查询到您的房屋信息',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('获取房屋信息失败', err);
        wx.showToast({
          title: '获取房屋信息失败',
          icon: 'none'
        });
      });
  },

  // 加载小区信息
  loadCommunities: function(communityIds) {
    const communityList = [];
    const totalCommunities = communityIds.length;
    let loadedCount = 0;

    communityIds.forEach(communityId => {
      // 使用https.get替换wx.request
      https.get(`opendoor/community/${communityId}`)
        .then(res => {
          if (res.code === 200 && res.data) {
            communityList.push(res.data);
          }
          loadedCount++;
          
          // 所有小区加载完成
          if (loadedCount === totalCommunities && communityList.length > 0) {
            this.setData({
              communityList,
              selectedCommunity: communityList[0],
              selectedCommunityIndex: 0
            });
            this.loadDoors(communityList[0].id);
          }
        })
        .catch(err => {
          console.error('获取小区信息失败', err);
          loadedCount++;
        });
    });
  },

  // 加载小区门列表
  loadDoors: function(communityId) {
    // 使用https.get替换wx.request
    https.get(`opendoor/doors/${communityId}`)
      .then(res => {
        if (res.code === 200) {
          this.setData({
            doorList: res.data,
            selectedDoor: 0
          });
        } else {
          this.setData({ doorList: [] });
          wx.showToast({
            title: '未查询到门信息',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('获取门列表失败', err);
        wx.showToast({
          title: '获取门列表失败',
          icon: 'none'
        });
      });
  },

  // 选择小区
  bindCommunityChange: function(e) {
    const index = e.detail.value;
    const selectedCommunity = this.data.communityList[index];
    
    this.setData({
      selectedCommunityIndex: index,
      selectedCommunity: selectedCommunity
    });
    
    // 加载选中小区的门列表
    this.loadDoors(selectedCommunity.id);
  },

  // 选择门
  selectDoor: function(e) {
    const index = parseInt(e.currentTarget.dataset.index);
    this.setData({
      selectedDoor: index,
      openSuccess: false
    });
  },

  // 开门操作
openDoor: function() {
  if (this.data.isOpening || this.data.doorList.length === 0) return;

  const door = this.data.doorList[this.data.selectedDoor];
  
  this.setData({
    isOpening: true,
    openSuccess: false
  });

  // 实际项目中使用https.post调用后端开门接口
  https.post('opendoor/open', { 
    doorId: door.id,
    residentId: this.data.residentId
  })
    .then(res => {
      if (res.code === 200) {
        this.setData({
          isOpening: false,
          openSuccess: true
        });
        wx.showToast({
          title: `${door.door} 已成功开启！`, // 修改这里：使用 door.door 而不是 door.doorName
          icon: 'success',
          duration: 2000
        });

        setTimeout(() => {
          this.setData({ openSuccess: false });
        }, 3000);
      } else {
        this.setData({ isOpening: false });
        wx.showToast({
          title: res.msg || '开门失败',
          icon: 'none'
        });
      }
    })
    .catch(err => {
      console.error('开门请求失败', err);
      this.setData({ isOpening: false });
      wx.showToast({
        title: '开门请求失败',
        icon: 'none'
      });
    });
},

  /**
   * 其他生命周期函数保持不变
   */
  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
})